package org.sky.framework.degest;

import java.util.Map;

import org.sky.framework.util.Utils;

/**
 * 摘要实体
 * 
 * @author gaofu
 *
 */
public class DigestEntity {

	/**
	 * 过期时间
	 */
	protected long exp;

	/**
	 * 签名
	 */
	protected String sign;

	/**
	 * 主体
	 */
	protected Map<String, Object> body;

	public DigestEntity() {
		resetExp();
	}

	/**
	 * 重置过期时间, 默认45分钟
	 */
	public void resetExp() {
		resetExp(defaultExp());
	}

	/**
	 * 重置过期时间/毫秒
	 */
	public void resetExp(long exp) {
		this.exp = System.currentTimeMillis() + exp;
	}

	/**
	 * 默认过期时间
	 * 
	 * @return
	 */
	protected long defaultExp() {
		return 1000 * 60 * 45;
	}

	/**
	 * 设置实体
	 * 
	 * @param obj
	 * @throws Exception
	 */
	public void setEntity(Object obj) throws Exception {
		body = Utils.objectToMap(obj);
	}

	/**
	 * 获取实体
	 * 
	 * @param clazz
	 * @return
	 * @throws Exception
	 */
	public <T> T getEntity(Class<T> clazz) throws Exception {
		return Utils.mapToObject(body, clazz);
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		sb.append("\"exp\":").append(exp);
		if (body != null) {
			String json = Utils.toSortJson(body);
			sb.append(",\"body\":").append(json);
		}
		sb.append("}");
		return sb.toString();
	}

	public long getExp() {
		return exp;
	}

	public void setExp(long exp) {
		this.exp = exp;
	}

	public String getSign() {
		return sign;
	}

	public void setSign(String sign) {
		this.sign = sign;
	}

	public Map<String, Object> getBody() {
		return body;
	}

	public void setBody(Map<String, Object> body) {
		this.body = body;
	}

}
